import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

//接口
import { getShoopData, getGoodsData } from '@/api/shop'

//引入约束文件
import { Ifoods, IGoods } from '@/interface/goods'

export default new Vuex.Store({
  state: {//数据
    // value: 0,
    shopData: {},
    //商品
    goodsList: []
  },
  getters: {
    //左侧导航
    sideBarList(state) {
      return state.goodsList.map((v: IGoods) => v.name)
    },
    //筛选选中的订单
    calFilterCount(state) {
      let temp: Array<Ifoods> = []
      //循环列表 筛选选中count大于0 的商品
      state.goodsList.forEach((v: IGoods) => v.foods.forEach((sub: Ifoods) => {
        if (sub.count && sub.count > 0) {
          temp.push(sub);
        }
      }))
      return temp;

    },
    //计算总的价格 getter可以用里面的方法
    calTotalPrice(state, getters) {
      return getters.calFilterCount.reduce((total: number, cur: any) =>
        total + cur.count * cur.price, 0).toFixed(2)
    },
    //计算总的数量 getter可以用里面的方法
    calTotalNum(state, getters) {
      return getters.calFilterCount.reduce((total: number, cur: any) =>
        total + cur.count, 0)
    },
    //计算属性结算文字
    minPrice(state, getters) {
      let text = "";
      if (getters.calTotalNum === 0) {
        text = '满20元起送'
      } else if (getters.calTotalPrice > 0 && getters.calTotalPrice < 20) {
        text = `t2差${(20 - getters.calTotalPrice).toFixed(2)}元配送`
      } else if (getters.calTotalPrice > 20) {
        text = '去结算'
      }
      return text;
    },

  },
  mutations: {//同步方法

    //店铺
    SET_SHOP_DATA(state, shopData) {
      state.shopData = shopData
    },
    //商品信息
    SET_GOODS_DATA(state, data) {
      state.goodsList = data
      // console.log('state.goodsList :>> ', state.goodsList);
    },
  },
  actions: {//异步
    //店铺信息
    get_shop_data({ commit }) {
      return new Promise(async (resolve, reject) => {
        //发送请求
        let res = await getShoopData()
        // console.log('res.data :>> ', res.data);
        //解构数据
        let { data } = res.data;

        //把数据存进VUEX中，调用mutations里面的同步方法
        commit('SET_SHOP_DATA', data)

        //外面调用就抛出去
        resolve(data)

      })

    },

    //商品信息
    get_goods_list({ commit }) {
      return new Promise(async (resolve) => {
        //发送请求
        let res = await getGoodsData()
        console.log('res.data :>> ', res.data);
        //解构数据
        let { goodsList } = res.data;
        //添加一个count属性
        goodsList.forEach((v: IGoods) => v.foods.forEach((subV: Ifoods) => subV.count = 0))

        // 把数据存进去
        commit('SET_GOODS_DATA', goodsList)
        //抛出去
        resolve(goodsList)
      })
    },


  },
  modules: {
  }
})
